using System.Reflection;
using SqlSugar;

namespace Gateway.SqlSugar.Splits;

public static class SplitTableExtension
{
    private static int _tailLength = 2;
    
    public static ISugarQueryable<T> MySplitTable<T>(this ISugarQueryable<T> client, object splitId)
    {
        return client.SplitTable(c => c.ContainsTableNames(GetTableName<T>(splitId)));
    }


    public static string GetTableName<T>(object value)
    {
        var customAttribute = typeof(T).GetCustomAttribute<SugarTable>();
        if (customAttribute == null)
            return typeof(T).Name;
        if (value.GetType().Equals(typeof(string)))
            return string.Format(customAttribute.TableName,
                (GetStringHashCode(value.ToString()) % 100).ToString()
                .PadLeft(_tailLength, '0'));
        return typeof(T).Name;
    }

    public static string GetTableNameSuffix(object value)
    {
        if (value is string)
            return
                (GetStringHashCode(value.ToString()) % 100).ToString()
                .PadLeft(_tailLength, '0');
        return "";
    }

    public static int GetStringHashCode(string value)
    {
        int stringHashCode = 0;
        if (value.Length > 0)
        {
            for (int index = 0; index < value.Length; ++index)
                stringHashCode = 31 * stringHashCode + (int)value[index];
        }

        Console.WriteLine(stringHashCode);
        return Math.Abs( stringHashCode);
    }
}